const vscode = require("vscode");
const GlobalVriable = require("../utils/globalVriable");
const Util = require("../utils/util");

/**
 * 跳转到定义
 * @param {any} document
 * @param {any} position
 * @param {any} token
 */
// eslint-disable-next-line no-unused-vars
function provideDefinition(document, position, token) {
    const fileName = document.fileName;
    const word = document.getText(document.getWordRangeAtPosition(position));
    const line = document.lineAt(position);

    if (/\\.*\.(Q|qml)$/.test(fileName)) {
        let functionInfoList = GlobalVriable.getAjjlFunctionLibrary(document);
        let definitionReg = new RegExp(`(Function|Sub)\\s*${word}\\s*\\(`, "g");
        let definitionReg2 = new RegExp(`(Dim|ReDim|DimEnv|Rem|Set|Global)\\s*${word}\\s*(:|\\r)`, "gi");
        let definitionReg3 = new RegExp(`(Function|Sub).*\(${word}\)`, "g");
        for (const infoNum in functionInfoList) {
            if (functionInfoList.hasOwnProperty(infoNum)) {
                let infoObj = functionInfoList[infoNum];
                if (definitionReg.test(infoObj["content"])) {
                    let definitionPosition = Util.getStringPosition(infoObj["content"], definitionReg, -1);
                    return new vscode.Location(vscode.Uri.file(infoObj["path"]), new vscode.Position(definitionPosition[0], definitionPosition[2].indexOf(word)));
                } else if (definitionReg2.test(infoObj["content"])) {
                    let definitionPosition = Util.getStringPosition(infoObj["content"], definitionReg2, line.lineNumber + 1);
                    return new vscode.Location(vscode.Uri.file(infoObj["path"]), new vscode.Position(definitionPosition[0], definitionPosition[2].indexOf(word)));
                } else if (definitionReg3.test(infoObj["content"])) {
                    let definitionPosition = Util.getStringPosition(infoObj["content"], definitionReg3, line.lineNumber + 1);
                    return new vscode.Location(vscode.Uri.file(infoObj["path"]), new vscode.Position(definitionPosition[0], definitionPosition[2].indexOf(word)));
                }
            }
        }
    }
}

/**
 * 注册如何实现跳转到定义，第一个参数表示仅对Q件生效
 * @param {any} context
 */
module.exports = function(context) {
    context.subscriptions.push(vscode.languages.registerDefinitionProvider(["q"], { provideDefinition }));
};